package com.example.ending_demo.servlet;

import com.example.ending_demo.model.Address;
import com.example.ending_demo.model.User;
import com.example.ending_demo.service.AddressService;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet(urlPatterns = "/AddressAddServlet")
public class AddressAddServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        String username = request.getParameter("username");
        String phone = request.getParameter("phone");
        String email = request.getParameter("email");
        String address = request.getParameter("address");

        Address addressObj = new Address();
        addressObj.setAddr_username(username);
        addressObj.setAddr_phone(phone);
        addressObj.setAddr_email(email);
        addressObj.setAddress(address);
        addressObj.setUser_id(user.getUser_id());

        AddressService addressService = new AddressService();

        try {
            addressService.addAddress(addressObj);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        response.sendRedirect("address_add.jsp");
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);

    }
}